import os
import json
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, request

from exts import db
from exts import mail
from exts import scheduler
from flask_cors import *


def register_logging(app):
    '''
    注册log
    :param app:
    :return:
    '''

    class RequestFormatter(logging.Formatter):
        def format(self, record):
            record.url = request.url
            record.remote_addr = request.remote_addr

    request_formatter = RequestFormatter(
        '[%(asctime)s] %(remote_addr)s requested %(url)s\n'
        '%(levelname)s in  %(module)s: %(message)s'
    )
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = RotatingFileHandler(os.path.join(app.config['BASE_LOG_PAPTH'], __name__ + '.log'),
                                       maxBytes=10 * 1024 * 1024, backupCount=10)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)


def register_extensions(app):
    '''
    注册扩展
    :param app:
    :return:
    '''
    db.init_app(app)
    mail.init_app(app)
    CORS(app, supports_credentials=True)  # 设置跨域


'''默认对象转json'''


def register_blueprints(app):
    '''
    注册蓝图
    :param app:
    :return:
    '''

    from .api import Api
    from .user_api import UserApi
    from .aps_api import Aps_api
    from .task_api import Task_api

    app.register_blueprint(Api, url_prefix='/api')
    app.register_blueprint(UserApi, url_prefix='/api/user')
    app.register_blueprint(Aps_api, url_prefix='/api/aps')
    app.register_blueprint(Task_api, url_prefix='/api/task')


def register_errors(app):
    @app.errorhandler(400)
    def bad_request(e):
        return '400', 400

    @app.errorhandler(404)
    def page_not_found(e):
        return '404', 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return '500', 500


def register_shell_context(app):
    pass


def register_template_context(app):
    pass


def register_request_handlers(app):
    @app.before_request
    def do_handle_something():
        pass

    @app.after_request
    def do_handle_response(resp):
        '''
        处理返回的response，没有的字段添加上
        :param resp:
        :return:
        '''
        try:
            res = json.loads(resp.data)
            if 'msg' not in res.keys():
                res['msg'] = 'ok'
            if 'data' not in res.keys():
                res['data'] = {}
            if 'code' not in res.keys():
                res['code'] = 0
            resp.data = json.dumps(res)
            return resp
        except:
            return resp


def configure_scheduler(app):
    '''
    定时器配置
    :param app:
    :return:
    '''
    scheduler.init_app(app)
    scheduler.start()

    # 加载任务，选择了第一次请求flask后端时加载，可以选择别的方式...
    @app.before_first_request
    def load_tasks():
        # 开启任务
        # from app import run_tasks
        pass


app = Flask(__name__, template_folder='./templates', static_url_path='', static_folder='./static')
app.config.from_object('app.config')
app.config.from_object('config_env')
if app.config['ENV'] == 'production':
    app.config.from_object('app.config.production')
elif app.config['ENV'] == 'testing':
    # testing
    app.config.from_object('app.config.testing')
else:
    # development
    app.config.from_object('app.config.development')

from . import models, views

# register_logging(app)
register_extensions(app)
register_blueprints(app)
# register_lcommands(app)
register_errors(app)
# register_shell_context(app)
# register_template_context(app)
register_request_handlers(app)
configure_scheduler(app)
